package com.analytical.www.fargment

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.analytical.www.MainActivity
import com.analytical.www.R
import com.analytical.www.adapter.AdapterSampleInput
import com.analytical.www.base.FragmentBase
import com.analytical.www.bean.BeanSample
import com.analytical.www.databinding.FragHomeBinding
import com.analytical.www.databinding.FragSampleInputBinding
import com.analytical.www.pop.PopInputSample
import com.analytical.www.util.StringUtils.log
import com.analytical.www.util.StringUtils.toast
import com.analytical.www.util.UtilFastClickAbort

/**
 *@Auther Shawn
 *创建时间：2023/12/24 12:34
 */
class FragSampleInput:FragmentBase(), AdapterSampleInput.ItemClickListener,
    PopInputSample.IActionListener {
    private lateinit var binding:FragSampleInputBinding
    private  var mData:MutableList<BeanSample> = mutableListOf()
    private var mSearchResult:MutableList<BeanSample> = mutableListOf()
    private var selectItem:BeanSample? = null

    private val mAdapter by lazy {
        val value = AdapterSampleInput(requireContext(),this)
        value
    }

    private val popInputSample by lazy {
        val value = PopInputSample(requireContext())
        value.listener = this
        value
    }

    override fun getLayoutId(): Int {
        return R.layout.frag_sample_input
    }

    override fun lazyLoad() {
        initRecycleData()
        binding = FragSampleInputBinding.bind(contentView)
        mAdapter.mData = mData
        binding.rlSample.apply {
            layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
            adapter = mAdapter
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun initRecycleData() {
        mData.add(BeanSample("汽油 202312a"))
        mData.add(BeanSample("汽油 202312a"))
        mData.add(BeanSample("柴油 0510a"))
        mData.add(BeanSample("大庆煤油-as20"))
        mData.add(BeanSample("正十六烷 1"))
        mData.add(BeanSample("汽油 202209"))
        mData.add(BeanSample("甲醇汽油 121"))
        mData.add(BeanSample("汽油 202312a"))
        mData.add(BeanSample("正十六烷 1"))
        mData.add(BeanSample("大庆煤油-as20"))
        mData.add(BeanSample("正十六烷 1"))
        mData.add(BeanSample("汽油 202209"))
        mData.add(BeanSample("甲醇汽油 121"))
        mData.add(BeanSample("汽油 202312a"))
        mData.add(BeanSample("大庆煤油-as20"))
        mData.add(BeanSample("正十六烷 1"))
        mData.add(BeanSample("汽油 202209"))
        mData.add(BeanSample("甲醇汽油 121"))
        mData.add(BeanSample("汽油 202312a"))
    }

    override fun getData() {
        if (context is MainActivity) {
            (context as MainActivity).changeTitle("样品名称输入")
        }
    }

    private fun hideSoftInput() {
        val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(binding.root?.windowToken, 0)
    }

    private fun startSearch() {
        val input = binding.etSearch.text.toString().trim()
        if (input.isEmpty()) {
            "请输入内容".toast()
            return
        }
        mSearchResult.clear()
        mSearchResult = mData.filter {
            it.name.contains(input)
        }.toMutableList()
        if (mSearchResult.isEmpty()) {
            "没有搜索到结果".toast()
            mAdapter.mData = mData
            mAdapter.notifyDataSetChanged()
            return
        }
        mAdapter.mData = mSearchResult
        mAdapter.notifyDataSetChanged()
    }

    override fun initClick() {
        binding.root.setOnClickListener {
            hideSoftInput()
        }
        binding.ll1.setOnClickListener {
            selectItem?.let {
                vmData?.taskLiveData?.postValue(it)
            }
            close()
        }
        binding.ll4.setOnClickListener {
            close()
        }
        binding.tvSearch.setOnClickListener {
            if(UtilFastClickAbort.isFastClick()){
                return@setOnClickListener
            }
            startSearch()
        }
        binding.tvSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                // 判断是否是回车键
                if ((event?.action == KeyEvent.ACTION_DOWN) && (actionId == KeyEvent.KEYCODE_ENTER)) {
                    if (UtilFastClickAbort.isFastClick()) {
                        return false
                    }
                    // 在这里处理回车键被点击时的逻辑 返回true表示已经处理了事件，false表示未处理
                    startSearch()
                    return true
                }
                // 返回false表示未处理该事件
                return false
            }
        })
        binding.tvSearch.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        binding.ivUp.setOnClickListener {
            if (mAdapter.selPos < 0) {
                mAdapter.selPos = mAdapter.itemCount - 1
                binding.rlSample.scrollToPosition(mAdapter.selPos)
            } else {
                mAdapter.selPos -= 1
            }
        }
        binding.ivDown.setOnClickListener {
            if (mAdapter.selPos == mAdapter.itemCount - 1) {
                mAdapter.selPos = 0
                binding.rlSample.scrollToPosition(mAdapter.selPos)
            } else {
                mAdapter.selPos += 1
            }
        }
        binding.ivDelete.setOnClickListener {
            if (mAdapter.selPos >= 0 && mAdapter.selPos < mAdapter.itemCount) {
                mAdapter.mData.removeAt(mAdapter.selPos)
                mAdapter.notifyDataSetChanged()
                "删除后的索引：${mAdapter.selPos}".log()
            }
        }
    }

    override fun onKeyCodeBack(): Boolean {
        close()
        return true
    }

    private fun close() {
        if (context is MainActivity) {
            (context as MainActivity).removeFullScreenFrag(FragSampleInput::class.java.name)
        }
    }

    override fun click(position: Int) {
        selectItem = mData[position]
        mAdapter.selPos = position
    }

    override fun onActionOk(input: String) {
        if (input.isNotEmpty()) {
            input.toast()
        }
    }

    override fun onActionNo() {

    }

    companion object{
        fun newInstance(): FragSampleInput {
            val args = Bundle()
            val fragment = FragSampleInput()
            fragment.arguments = args
            return fragment
        }
    }
}